package com.system.server.impl;

import com.system.dao.UserDao;
import com.system.pojo.UserLogin;
import com.system.server.UserService;
import exception.LoginError;
import exception.OldPasswordError;
import exception.passwordDiffError;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Set;

/**
 * @Author: E-mail:
 * @Version: 创建时间：2019年04月09日19:22
 * @Description: <描述>
 */
@Service
@Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    public UserLogin findUserByUsernameAndPassword(String username, String password) throws LoginError {
        UserLogin userLogin = userDao.selectUser(username,password);
        if(userLogin == null) {
            throw new LoginError("用户名或者密码错误");
        }
        return userLogin;
    }

    @Override
    public void updatePassword(String oldPassword, String newPassword,String aginaNewPassword, Integer userID) throws OldPasswordError, passwordDiffError {
        //检查旧密码是否正确
        UserLogin userLogin = userDao.findStubyId(userID);
        System.out.println(userLogin.getPassword());
        System.out.println(oldPassword);
        System.out.println(userLogin.getPassword().equals(oldPassword));

        if(!userLogin.getPassword().equals(oldPassword)) {
            throw new OldPasswordError("旧密码输入错误");
        } else if(!newPassword.equals(aginaNewPassword)){
            throw new passwordDiffError("两次输入的密码不相同");
        } else {
            //修改密码
            userDao.updatePassword(newPassword,userID);
        }
    }

    @Override
    public Set<String> findRolesByName(String userName) {
        Set<String> roles = userDao.selectRolesByName(userName);
        return roles;
    }

    @Override
    public UserLogin findUserLoginByName(String loginName) {
        UserLogin userLogin = userDao.findUserLoginByName(loginName);
        return userLogin;
    }


}
